package com.pangu.util;

import android.util.Patterns;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * String类的工具类
 * Created by cxlin on 2015/7/15.
 */
public class StringUtil {

    /**
     * 是否是空字符串
     *
     * @param str
     * @return
     */
    public static boolean isEmptyString(String str) {
        return (str == null || str.trim().length() == 0);
    }

    /**
     * 判断字符串内容是否为数字
     *
     * @param content
     * @return
     */
    public static boolean isDigital(String content) {
        for (int i = 0; i < content.length(); i++) {
            if (!Character.isDigit(content.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 编码url
     */
    public static String encodeContentForUrl(String content) {
        try {
            return (content == null ? "" : URLEncoder.encode(content, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * 编码url
     */
    public static String decodeContentForUrl(String content) {
        try {
            return (content == null ? "" : URLDecoder.decode(content, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    public static boolean isValidEmail(String email) {
        boolean isValid = false;

        String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
        CharSequence inputStr = email;

        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

    public static boolean isValidPhoneNumber(String phoneNumber) {
        if (phoneNumber == null) {
            return false;
        } else {
            if (phoneNumber.length() < 6 || phoneNumber.length() > 13) {
                return false;
            } else {
                return Patterns.PHONE.matcher(phoneNumber).matches();
            }
        }
    }

    public static boolean isChineseText(String str){
        int length = str.length();
        for (int i = 0; i < length; i++){
            char ch = str.charAt(i);
            Character.UnicodeBlock block = Character.UnicodeBlock.of(ch);
            if (Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS.equals(block)||
                    Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS.equals(block)||
                    Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A.equals(block)){
                return true;
            }
        }
        return false;
    }
}
